package yang.VirtualMachine.chapter11.asm;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class AddSecurityCheckClassAdapter extends ClassVisitor {
	
	private String enhancedSuperName;

	public AddSecurityCheckClassAdapter(ClassVisitor cv) {
		// Responsechain 的下一个ClassVisitor,这里我们将传入ClassWriter, 负责改写后代码的输出
		super(Opcodes.ASM5, cv);
	}
	
	@Override
	public void visit(final int version, final int access, final String name, 
	        final String signature, final String superName, 
	        final String[] interfaces) { 
	    String enhancedName = name + "$EnhancedByASM";  // 改变类命名
	    enhancedSuperName = name; // 改变父类，这里是”Account”
	    super.visit(version, access, enhancedName, signature, 
	    enhancedSuperName, interfaces); 
	}
	
	@Override
	public MethodVisitor visitMethod(final int access, final String name
			, final String desc, final String signature, final String[] exceptions) {
		MethodVisitor mv = cv.visitMethod(access, name, desc, signature, exceptions);
		
		MethodVisitor wrappedMv = mv;
		if (mv != null) {
			if (name.equals("operation")) {
				wrappedMv = new AddSecurityCheckMethodAdapter(mv);
			} else if (name.equals("<init>")) {
				// 将此类改为Account的子类
				wrappedMv = new ChangeToChildConstructorMethodAdapter(mv, enhancedSuperName);
			}
		}
		return wrappedMv;
	}

}
